  
/**
 * 1.获取部门和职务 并行获取
 * 2.获取用户输入信息，校验，通过后发送服务器
 */
let useraddModule = (function () { 
    let $username = $('.username'),
        $spanusername = $('.spanusername'),
        $man = $('#man'),
        $woman = $('#woman'),
        $useremail = $('.useremail'),
        $spanuseremail = $('.spanuseremail'),
        $userphone = $('.userphone'),
        $spanuserphone = $('.spanuserphone'),
        $userdepartment = $('.userdepartment'),
        $userjob = $('.userjob'),
        $userdesc = $('.userdesc'),
        $submit = $('.submit')
    let userid = null
    // 绑定部门和职务的信息
    async function bindDepartAndJob() { 
        // 读取缓存的数据
        let departmentData = await queryDepart()
        let jobData = await queryJob()

        if (departmentData.code == 0) {
            departmentData = departmentData.data
            let str = ``
            departmentData.forEach(item => {
                str+=` <option value="${item.id}">${item.name}</option>`
            })
            $userdepartment.html(str) 
        } 
        if (jobData.code == 0) {
            jobData = jobData.data
            let str = ``
            jobData.forEach(item => {
                str+=` <option value="${item.id}">${item.name}</option>`
            })
            $userjob.html(str) 
        }  
    }

    // 表单校验
    function checkName() {
        let val = $username.val().trim()
        if (val.length === 0) {
            $spanusername.html('当前是必填项')
            return false
        }
        if (!/^[\u4E00-\u9FA5]{2,10}(·[\u4E00-\u9FA5]{2,10}){0,2}$/.test(val)) {
            $spanusername.html('请填写真实姓名（2-10个汉字）')
            return false
        }
        $spanusername.html('')
        return true
    }
    function checkEmail() {
        let val = $useremail.val().trim()
        if (val.length === 0) {
            $spanuseremail.html('当前是必填项')
            return false
        }
        if (!/^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(val)) {
            $spanuseremail.html('请填写真实Email')
            return false
        }
        $spanuseremail.html('')
        return true
    }
    function checkPhone() { 
        let val = $userphone.val().trim() 
        if (val.length === 0) {
            $spanuserphone.html('当前是必填项')
            return false
        } 
        if (!/^1\d{10}$/.test(val)) {
            $spanuserphone.html('请填写真实手机号')
            return false
        }
        $spanuserphone.html('')
        return true
    }

    // 点击确认提交按钮
    async function submitHandle() {
        if (!checkName() || !checkEmail() || !checkPhone()) return 
        // 获取用户输入的信息
        let params = {
            name: $username.val().trim(),
            sex: $man.prop('checked') ? 0 : 1,
            email:$useremail.val().trim(),
            phone:$userphone.val().trim(),
            departmentId:$userdepartment.val(),
            jobId:$userjob.val(),
            desc:$userdesc.val().trim()
        } 
        // 向服务器发送请求 (区分新增和修改)
        if (userid) {
            params.userId = userid 
            let result = await axios.post('/user/update', params)
            if (result.code == 0) {
                alert('修改成功！')
                window.location.href = 'userlist.html'
                return;
            }
            alert('当前网络繁忙，请刷新重试~~')
            return
        }
        let result = await axios.post('/user/add', params)   
        if (result.code == 0) {
            alert('添加成功！')
            window.location.href = 'userlist.html'
            return;
        }
        alert('当前网络繁忙，请刷新重试~~')

        window.location.href = 'userlist.html'

    }

    // 修改读取数据
    async function queryBaseInfo() {
        // /user/info get
        let result = await axios.get('/user/info', {
            params: {
                userId:userid
            }
        })
        if (result.code == 0) {
            let {name,sex,email,phone,departmentId,jobId,desc} = result.data
            $username.val(name)
            parseInt(sex) ===0 ? $man.prop('checked',true):$woman.prop('checked',true)
            $useremail.val(email) 
            $userphone.val(phone)
            $userdepartment.val(departmentId)
            $userjob.val(jobId)
            $userdesc.val(desc)
            return
        }
        alert('当前编辑的员工不存在，请查证！')
        window.location.href='userlist.html'
    }
    return {
        init() {
            // 绑定职务和部门
            bindDepartAndJob()
            //通过判断url参数，确定是编辑还是新增
            let params = window.location.href.queryURLParams()
            if (params.hasOwnProperty('userid')) {
                userid = params.userid
                queryBaseInfo()
            } 
            //文本失去焦校验
            $username.blur(checkName)
            $useremail.blur(checkEmail)
            $userphone.blur(checkPhone) 
            // 提交按钮
            $submit.click(submitHandle)
        }
    }
})()
useraddModule.init()